package com.wheel.logging.appender;/*
 * <h3>Title:wheel-service-ant系统</h3>
 * <p>Copyright (c) 2021, wnfbx@163.com. All rights reserved.</p>
 * @author wnfbx@163.com
 */

import ch.qos.logback.core.OutputStreamAppender;
import ch.qos.logback.core.status.ErrorStatus;
import com.wheel.logging.ws.server.LogSessionManager;
import org.springframework.beans.factory.annotation.Autowired;

import javax.websocket.Session;
import java.io.IOException;
import java.io.OutputStream;

/**
 * <dt>Description:LoggingAutoConfig</dt>
 * <dd>日志自动配置</dd>
 *
 * @author wnfbx@163.com
 * @version 1.0 <i>2021/1/31 23:12</i>
 * @since jdk1.7+
 */
public class WebSocketLogbackAppender<E> extends OutputStreamAppender<E> {

    private Session session;
    public WebSocketLogbackAppender() {
       session = LogSessionManager.getInstance().getSession();
    }

    @Autowired
    public void subAppend(E event){
        if(session==null){
            return;
        }
        OutputStream outputStream = getOutputStream();
        if (outputStream == null) {
            //不考虑并发，outputstream只有一个
            try {
                setOutputStream(session.getBasicRemote().getSendStream());
            } catch (IOException e) {
            }
        }
        super.subAppend(event);
    }

    @Autowired
    public void start() {
        int errors = 0;
        if (this.encoder == null) {
            addStatus(new ErrorStatus("No encoder set for the appender named \"" + name + "\".", this));
            errors++;
        }

        // only error free appenders should be activated
        if (errors == 0) {
            //super.super.start()
            started = true;
        }
    }
}